public class test03 {
    class Solution {
        public int[][] merge(int[][] intervals) {
            Arrays.sort(intervals,(a,b)->Integer.compare(a[0],b[0]));
            List<int[]> res = new ArrayList<>();
            int rightRange = intervals[0][1];
            int leftRange = intervals[0][0];
            for(int i = 1;i<intervals.length;i++){
                if(rightRange>=intervals[i][0]){
                    leftRange = Math.min(leftRange,intervals[i][0]);
                    rightRange = Math.max(rightRange,intervals[i][1]);
                }else{
                    res.add(new int[]{leftRange,rightRange});
                    leftRange = intervals[i][0];
                    rightRange = intervals[i][1];
                }
            }
            res.add(new int[]{leftRange,rightRange});

            return res.toArray(new int[res.size()][2]);
        }
    }
}
